package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user/addressBook")
@Slf4j
@Api(tags = "关于地址的接口")
public class AddressBookeController {
    @Autowired
    private AddressBookService adressBookService;

    @PostMapping
    @ApiOperation("新增地址")
    public Result add(@RequestBody AddressBook addressBook){

        adressBookService.add(addressBook);
        return Result.success();
    }


    @GetMapping("list")
    @ApiOperation("查询当前用户的所有登录信息")
    public Result<List<AddressBook>> list() {
      List<AddressBook> addressBooks =  adressBookService.list();
        return Result.success(addressBooks);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> getById(@PathVariable Long id){
       AddressBook addressBook =  adressBookService.getById(id);
       return Result.success(addressBook);
    }


    @PutMapping
    @ApiOperation("根据id修改地址信息")
    public Result put(@RequestBody AddressBook addressBook){
        adressBookService.putById(addressBook);
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("根据id删除地址")
    public Result remove(Long id){
        adressBookService.removeById(id);
        return Result.success();
    }

    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setDefault(@RequestBody AddressBook addressBook){
        adressBookService.setDefault(addressBook);
        return Result.success();
    }

    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> get(){
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
       List<AddressBook> addressBookList =  adressBookService.get(addressBook);
       if (addressBookList != null && addressBookList.size()>0){
           return Result.success(addressBookList.get(0));
       }
       return Result.error("没有默认地址");
    }
}
